const Video = require('../model/video.model');
// 使用模糊查询需要先引入Op
const seq = require('sequelize');
const Op = seq.Op;

// 服务层 读写数据库
class VideoService {
    // 添加视频
    async createVideo(video_name, video_desc, video_url, banner_url, video_type, video_source) {
        // Video.create({
        //     video_name: video_name,
        //     video_desc: video_desc
        // });
        // 属性和值一样可以简写
        let res = await Video.create({video_name, video_desc, video_url, banner_url, video_type, video_source});
        return res;
    }

    async getVideoInfo({id, video_name, video_source, video_type, flag, pageInfo}) {
        let whereObj = {};
        id && Object.assign(whereObj, {id});

        video_source && Object.assign(whereObj, {video_source});
        video_type && Object.assign(whereObj, {video_type});
        flag && Object.assign(whereObj, {flag});

        video_name && Object.assign(whereObj, {
            video_name: {
                [Op.like]: `%${video_name}%`
            },
        });

        // 查数量
        let count = await Video.count({where: whereObj});
        let res;
        if (count !== 0) {
            let _pageInfo = {};
            if (pageInfo) {
                let {pageIndex, pageSize} = JSON.parse(pageInfo);
                _pageInfo = {
                    limit: pageSize,
                    offset: (pageIndex - 1) * pageSize
                }
            }
            res = await Video.findAll({
                where: whereObj,
                ..._pageInfo
            });
        }
        return {list: res, count: count} || null;
    }

    async updateVideoInfo({id, video_name, video_desc, video_url, banner_url, video_type, video_source, flag}) {

        let whereObj = {id};
        let newVideo = {};
        video_name && Object.assign(newVideo, {video_name});
        video_desc && Object.assign(newVideo, {video_desc});
        video_url && Object.assign(newVideo, {video_url});
        banner_url && Object.assign(newVideo, {banner_url});
        video_type && Object.assign(newVideo, {video_type});
        video_source && Object.assign(newVideo, {video_source});
        flag && Object.assign(newVideo, {flag});
        let res = await Video.update(newVideo, {
            where: whereObj
        });
        return res[0] > 0;
    }
}

module.exports = new VideoService();